/**
 * 合同模版
 */
var pageBean = null;
var dataList = {};
var spaces = {};
$(document).ready(function(e) {
	
	$("#btnTemplteAdd").click(add);
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	initialSpace();
	search(1);	
	
})

/**
 *清空搜索条件 
 */
function searchReset(){
	var contractType= $("#searchcontractType");
	var status= $("#searchStatus");
	var spaceId= $("#searchSpace");	
	var firstVal = $(contractType).find('option').eq(0).val();				
	$(contractType).val(firstVal).trigger('change');
	
	firstVal = $(status).find('option').eq(0).val();				
	$(status).val(firstVal).trigger('change');
	
	firstVal = $(spaceId).find('option').eq(0).val();				
	$(spaceId).val(firstVal).trigger('change');
}

function add(){
	$("#operate").html("添加");
	clearForm();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();

	$("#contractTypeForm").val(-1);
	$("#spaceIdForm").val(-1);

}

function clearForm(){
	$("[formParameter='contractTemplete']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				var firstVal = $(element).find('option').eq(0).val();				
				$(element).val(firstVal).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function setForm(contractTemplete){
	$("[formParameter='contractTemplete']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				$(element).val(contractTemplete[name]).trigger('change');
			}else{
				$(element).val(contractTemplete[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function enable(id){	
	var mContractTemplate = dataList[id];
	mContractTemplate['status'] = '1';
	$.ajax({
        url: '/euc/contracttemplate/enable',
        data:JSON.stringify(mContractTemplate),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
            	alert(datas.message);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/update error");
        }
    });
}

function disable(id){	
	var mContractTemplate = dataList[id];
	mContractTemplate['status'] = '2';
	$.ajax({
        url: '/euc/contracttemplate/update',
        data:JSON.stringify(mContractTemplate),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
            	alert('禁用成功！');
        	}else{
        		alert('禁用失败！');
        	}        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/update error");
        }
    });
}

function detail(id){	
	clearForm();
	setForm(dataList[id]);
	$("#operator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();	
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		update(dataList[id]);
	});
}

function update(contractTemplete){
	if(contractTemplete == null){
		return false;
	}
	contractTemplete = getRequestJson(contractTemplete);
	if(contractTemplete == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/contracttemplate/update',
        data:JSON.stringify(contractTemplete),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/update error");
        }
    });
}

function getRequestJson(contractTemplete){	
	if(contractTemplete == null){
		contractTemplete = {};
	}
	var contractTypeForm = $("#contractTypeForm").val();
	if(contractTypeForm == '-1'){
        alert("请选择合同类型");
		return false;
	}
	var spaceIdForm = $("#spaceIdForm").val();
	if(spaceIdForm == '-1'){
		alert("请选择所属空间");
		return false;
	}
	$("[formParameter='contractTemplete']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				contractTemplete = false;
				return false;
			}
			if(name == 'contractType'){
				contractTemplete['contractTypeName'] = $(this).find('option[value='+val+']').text();
			}else if(name == 'spaceId'){
				contractTemplete['spaceName'] = $(this).find('option[value='+val+']').text();
			}
			contractTemplete[name] = val;
		}catch(e){
			console.log(e.messge);
		}
	});
	return contractTemplete;
}

function save(){
	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/contracttemplate/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/add error");
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
}

function getSearchParameter(currentPage){
	try{
		var contractType= $("#searchcontractType").val();
		var status= $("#searchStatus").val();
		var spaceId= $("#searchSpace").val();
		if(contractType == '0'){
			contractType = '';
		}
		if(status == '0'){
			status = '';
		}
		if(spaceId == '0'){
			spaceId = '';
		}
		var requestJson = {'contractType':contractType,'status':status,'spaceId':spaceId};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}


function search(currentPage){

	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	var requestJson = {currentPage:currentPage,data:{'like':{},'equals':requestJson}}; 
	$.ajax({
        url: '/euc/contracttemplate/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
                var html = '<tr>';
                html += '<td style="width:160px;">' + $.trim(data.contractTypeName) + '</td>';
                html += '<td>' + $.trim(data.spaceName) + '</td>';
                html += '<td>' + $.trim(data.partyBName) + '</td>';
                html += '<td>' + $.trim(data.partyBAddress) + '</td>';
                html += '<td>' + $.trim(data.partyBContact) + '</td>';
                html += '<td>' + $.trim(data.partyBContactNumber) + '</td>';
                html += '<td>' + $.trim(data.partyBEmail) + '</td>';
                html += '<td>' + $.trim(data.lastModifyTime) + '</td>';
                if($.trim(data.status) == '2'){
                	html += '<td>已停用</td>';
                }else if($.trim(data.status) == '1'){
                	html += '<td>已启用</td>';
                }
                html += '<td style="width:170px;">';
                if($.trim(data.status) == '2'){
                	html += '<a href="javascript:enable('+data.id+');" class="tablelink">启用</a>&nbsp;&nbsp;&nbsp;';
                	html += '<a href="javascript:detail('+data.id+');" class="tablelink">编辑</a></td>';
                }else if($.trim(data.status) == '1'){
                	html += '<a href="javascript:disable('+data.id+');" class="tablelink">禁用</a>&nbsp;&nbsp;&nbsp;';
                }                
                html += '</tr>';
                $("#userTable").append(html);
                dataList[data.id] = data;   
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/query error");
        }  
    });
}

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

/*空间名称*/
function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	var spaceSelect = $("#searchSpace");
	var spaceId = $("#spaceIdForm");
	$.each(spaces,function(key,space){
		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceId));
	});
	
}